/*
 * Copyright (C) 2010, Funcom AS, All Rights Reserved
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *  @authors
 *  Svein Gunnar Larsen <sveingunnarlarsen@gmail.com>
 *  Erik Thune Lund <culex.eriklund@gmail.com>
 *  Michel Krohn-Dale <kronicz@gmail.com>
 */

package com.funcom.peeler.utils;

import com.funcom.peeler.ExtensionFileFilter;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.io.File;
import static com.funcom.peeler.UpdateCont.get;
import static com.funcom.peeler.utils.RelativePath.getRelativeFile;

/**
 * File Chooser with Image FileFilter
 */
public class FileChooser {

    private static JFileChooser fileChooser;

    /**
     * Utility function to select file and make path relative
     * @return returns the selected file or null
     */
    public static String selectFile() {

        if (fileChooser == null) initChooser();

        int retval = fileChooser.showOpenDialog(null);

            if (retval == JFileChooser.APPROVE_OPTION) {

                String pathToFile = fileChooser.getSelectedFile().getPath();
                File file = new File(pathToFile);
                file = getRelativeFile(file, new File(get().getFocusedWorkBench().getBasePath()));
                String backslash = System.getProperty("file.separator");
                pathToFile = file.getPath();
                pathToFile = pathToFile.replace(backslash, "/");

                return pathToFile;

        } else {
            return null;
        }
    }

    /**
     * Initializes FileChooser and sets a FileFilter for images
     */
    public static void initChooser() {
        String startDir = get().getFocusedWorkBench() == null ? null : get().getFocusedWorkBench().getBasePath();

        //Add other extensions if needed
        FileFilter imageFilter = new ExtensionFileFilter("Images", new String[]{ "jpg", "gif", "png", "bmp", "jpeg"});
        
        fileChooser = new JFileChooser(startDir);
        fileChooser.setFileFilter(imageFilter);
        fileChooser.setAcceptAllFileFilterUsed(false);
    }
}
